package cz.movie.subRenamer.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import org.apache.commons.io.IOUtils;

public class ZipUtil {

	public static void extraxtZipToDir(File source, File outputDir) throws ZipException, IOException {
		extraxtZipToDir(source, outputDir, false);
	}

	public static void extraxtZipToDir(File source, File outputDir, boolean allToOneDir) throws ZipException, IOException {
		outputDir.mkdirs();
		if (!outputDir.exists() && !outputDir.isDirectory()) {
			throw new RuntimeException("Cannot create dir: " + outputDir);
		}
		ZipFile zipFile = new ZipFile(source);
		Enumeration<? extends ZipEntry> entries = zipFile.entries();
		while (entries.hasMoreElements()) {
			ZipEntry nextElement = entries.nextElement();
			InputStream inputStream = null;
			FileOutputStream fileOutputStream = null;
			String extractedFileName = nextElement.getName();
			if (allToOneDir) {
				extractedFileName = extractedFileName.replaceAll(".*/", "");
				if (nextElement.isDirectory()) {
					continue;
				}
			} else {
				if (nextElement.isDirectory()) {
					new File(outputDir, extractedFileName).mkdirs();
					continue;
				}
			}
			try {
				inputStream = zipFile.getInputStream(nextElement);
				File file = new File(outputDir, extractedFileName);
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				file.createNewFile();
				fileOutputStream = new FileOutputStream(file);
				IOUtils.copy(inputStream, fileOutputStream);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				IOUtils.closeQuietly(inputStream);
				IOUtils.closeQuietly(fileOutputStream);
			}
		}
	}
}
